ATOM Documentation

← Back to App

Telegram Integration Testing Guide

**Phase:** 37 OpenClaw Integration

**Last Updated:** 2026-02-16

Overview

This guide walks through testing the Telegram bot integration for Atom Agent OS, including account linking, command execution, and response formatting.

Prerequisites

1. Environment Setup

Ensure you have:

  • Atom backend running (http://localhost:8000 or https://api.atomagentos.com)
  • PostgreSQL database with migrations applied
  • Redis instance running (for account linking tokens)
  • Existing tenant and user account in Atom

2. Required Environment Variables

Create or update .env file in backend-saas/:

# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN=your_bot_token_here

# Redis Configuration (for account linking)
REDIS_URL=redis://localhost:6379/0
# Or use Upstash REST API:
# REDIS_URL=https://your-redis-url.upstash.io

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/atomdb

# Application
PORT=8000
LOG_LEVEL=INFO

3. Install Python Dependencies

cd backend-saas
pip install python-telegram-bot==22.0
pip install redis

Step 1: Create Telegram Bot

1.1. Start Conversation with BotFather

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow prompts:
  • Choose a name: Atom Agent OS Test Bot
  • Choose a username: atom_test_bot_12345 (must be unique)
  1. BotFather will provide a token like:

Send these commands to @BotFather:

/setprivacy
→ Select your bot
→ Disable

**Why:** Allows bot to read all messages in groups (useful for testing)

/setcommands
→ Select your bot
→ Paste command list:

start - Start using Atom Agent OS
link - Link your Telegram account to Atom
help - Show available commands
status - Check agent status

Step 2: Configure Webhook

2.1. Get Webhook URL

**Local Development (with ngrok):**

# Install ngrok
brew install ngrok

# Start ngrok tunnel
ngrok http 8000

# Use the HTTPS URL provided:
# https://abc123.ngrok.io

**Production (Managed Cloud):**

https://api.atomagentos.com

2.2. Set Webhook via API

curl -X POST "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-domain.com/api/gateway/webhook/telegram"
  }'

**Replace:**

  • <TELEGRAM_BOT_TOKEN> with your actual token
  • https://your-domain.com with your domain

2.3. Verify Webhook

curl "https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/getWebhookInfo"

Expected response:

{
  "ok": true,
  "result": {
    "url": "https://your-domain.com/api/gateway/webhook/telegram",
    "has_custom_certificate": false,
    "pending_update_count": 0
  }
}
curl -X POST "http://localhost:8000/api/gateway/link/telegram" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "your-tenant-user-id"
  }'

Expected response:

{
  "token": "abc123def456",
  "expires_at": "2026-02-16T03:00:00Z"
}

Send this message to your bot:

/link abc123def456

Or use the backend API:

curl -X POST "http://localhost:8000/api/gateway/confirm-link" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "abc123def456",
    "chat_id": "your_telegram_chat_id"
  }'

**How to get your chat_id:**

  1. Send /start to your bot
  2. Visit: https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/getUpdates
  3. Find "chat":{"id":123456789} in the response

3.3. Verify Linking

Check database or call:

curl "http://localhost:8000/api/gateway/linked-accounts?user_id=your-user-id"

Step 4: Test Command Execution

4.1. Create Test Agent

First, ensure you have an agent in Atom:

curl -X POST "http://localhost:8000/api/agents" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Finance",
    "category": "Operations",
    "maturity_level": "supervised",
    "description": "Finance operations agent"
  }'

4.2. Send Command via Telegram

Send this message to your bot:

/run Finance show status

4.3. Expected Flow

  1. **Bot responds immediately:** Typing indicator
  2. **Bot processes:** Parses intent, checks governance, executes agent
  3. **Bot responds with result:**
🤖 Executing Finance agent...

✅ Task completed in 2.5s

Status: All systems operational
Budget: $45,000 / $50,000
Active alerts: 0

Step 5: Test Rich Features

5.1. Test Rich Formatting

/run Finance generate report --format json

Expected: Code blocks with syntax highlighting

5.2. Test Media Support

/run Finance export chart --type png

Expected: Image file sent back

5.3. Test Dangerous Commands (2FA)

/run Finance delete_all_data

Expected:

⚠️ Dangerous command detected!

2FA required. Check your email for confirmation token.

Reply with: /confirm <token>

Step 6: Test Rate Limiting

Send multiple commands rapidly:

/run Finance status
/run Finance status
/run Finance status
...

After hitting limit (Free: 10/minute):

⚠️ Rate limit exceeded!

You've exceeded your plan's rate limit.
Free plan: 50 commands/day, 10/minute
Upgrade: https://atom-saas.com/upgrade

Step 7: Test Account Linking UI (Frontend)

7.1. Access Dashboard

  1. Open Atom dashboard: http://localhost:3000
  2. Navigate to Settings → Integrations → Telegram
  3. Click "Link Telegram Account"

7.2. Scan QR Code

  1. Dashboard shows QR code
  2. Send /link command to bot
  3. Bot responds with QR code scan option
  4. Scan with Telegram app

7.3. Verify Linked Account

Dashboard shows:

Linked Accounts:
✅ Telegram (@your_username)
  Linked: Feb 16, 2026
  Chat ID: 123456789

Troubleshooting

Issue: Webhook Not Receiving Updates

**Symptoms:** Bot doesn't respond to messages

**Solutions:**

  1. Verify webhook URL: curl https://api.telegram.org/bot<token>/getWebhookInfo
  2. Check backend logs: tail -f backend-saas/logs/app.log
  3. Ensure backend is running: curl http://localhost:8000/api/gateway/health
  4. Check firewall/ngrok is running

Issue: Account Linking Fails

**Symptoms:** /link command returns "Invalid token"

**Solutions:**

  1. Check token hasn't expired (1-hour expiry)
  2. Verify Redis is running: redis-cli ping
  3. Check backend logs for specific error
  4. Regenerate token via API

Issue: Command Execution Fails

**Symptoms:** Bot returns error instead of result

**Solutions:**

  1. Check agent exists and is active
  2. Verify tenant_id matches
  3. Check governance logs: Agent maturity too low?
  4. Review shell command approval (if applicable)

Issue: Rate Limiting Too Aggressive

**Symptoms:** Legitimate usage blocked

**Solutions:**

  1. Check Redis rate limit keys: redis-cli keys "rate:*"
  2. Verify plan tier in database
  3. Clear stale keys: redis-cli DEL rate:tenant:<tenant_id>
  4. Adjust limits in abuse_protection_service.py

Debugging Commands

Check Bot Status

# Health check
curl http://localhost:8000/api/gateway/health

# Webhook info
curl "https://api.telegram.org/bot<token>/getWebhookInfo"

# Recent updates
curl "https://api.telegram.org/bot<token>/getUpdates?offset=-1"

View Redis State

# Link tokens
redis-cli keys "link:*"

# Rate limit counters
redis-cli keys "rate:*"

# View specific token
redis-cli GET "link:abc123def456"

Database Queries

-- Check linked accounts
SELECT * FROM user_accounts WHERE platform = 'telegram';

-- Check audit log
SELECT * FROM im_audit_log ORDER BY created_at DESC LIMIT 10;

-- Check link tokens
SELECT * FROM link_tokens WHERE used_at IS NULL;

Performance Testing

Load Test Command Execution

# Install hey (HTTP load generator)
go install github.com/rakyll/hey@latest

# Test webhook endpoint (100 requests, 10 concurrent)
hey -n 100 -c 10 -H "Content-Type: application/json" \
  -d '{"update_id":1,"message":{"chat":{"id":123456789},"text":"test"}}' \
  http://localhost:8000/api/gateway/webhook/telegram

Monitor Response Times

# Check backend logs for timing
tail -f backend-saas/logs/app.log | grep "duration_ms"

Next Steps

After successful testing:

  1. **Deploy to Production:** Update webhook URL to production domain
  2. **Monitor Logs:** Set up log aggregation (Sentry, LogRocket)
  3. **Configure Alerts:** Rate limit alerts, error rate alerts
  4. **Scale Up:** Add Redis replica for token storage
  5. **Add More Platforms:** WhatsApp (Twilio), Signal (signal-cli)

Additional Resources

  • **Telegram Bot API Docs:** https://core.telegram.org/bots/api
  • **python-telegram-bot Docs:** https://python-telegram-bot.readthedocs.io/
  • **Phase 37 Plans:** .planning/phases/37-openclaw-integration/
  • **Message Gateway Code:** backend-saas/core/message_gateway.py

Checklist

  • [ ] Telegram bot created via @BotFather
  • [ ] Bot token added to environment variables
  • [ ] Webhook URL configured
  • [ ] Backend server running with migrations applied
  • [ ] Redis instance running
  • [ ] Account linking flow tested (token generation → linking)
  • [ ] Command execution tested (simple command)
  • [ ] Rich formatting tested (markdown, code blocks)
  • [ ] Rate limiting tested (multiple rapid commands)
  • [ ] 2FA flow tested (dangerous command)
  • [ ] Dashboard UI tested (QR code scanning)
  • [ ] Logs reviewed for errors
  • [ ] Production webhook URL set (if deploying)

---

**Questions?** Check the Phase 37 summary documents or review the implementation code.